package com.apes.crm.car.service;

import com.apes.crm.car.model.CarTypeLimit;
import com.apes.crm.car.repository.CarTypeLimitRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.area.model.Area;
import com.apes.scm.masterdata.product.model.Classify;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("carTypeLimitService")
public class CarTypeLimitService extends DomainService {

    @Autowired
    CarTypeLimitRepository carTypeLimitRepository;


    /**
     * 创建车型限制
     *
     * @param request
     * @return
     */
    public CarTypeLimit create(SimpleRequest request) {
        CarTypeLimit carTypeLimit = request.getO(CarTypeLimit.class);
        checkUnique(carTypeLimit);  // 限制重复录入
        return carTypeLimitRepository.saveAndFlush(carTypeLimit);
    }

    /***
     * 修改车型限制
     * @param request
     * @return
     */
    public CarTypeLimit update(SimpleRequest request) {
        CarTypeLimit carTypeLimit = request.getO(CarTypeLimit.class);
        checkUnique(carTypeLimit); // 限制重复录入
        return carTypeLimitRepository.saveAndFlush(carTypeLimit);
    }

    /**
     * 功能：删除限制
     */
    public String delete(SimpleRequest request) {
        String id = request.get("id");
        CarTypeLimit carTypeLimit = carTypeLimitRepository.findOne(id);
        if (carTypeLimit == null) throw new RuntimeException("限制：" + request.get("id") + " 在系统中不存在。");
        carTypeLimitRepository.delete(carTypeLimit);
        return "删除成功！";
    }

    /***
     * 限制重复录入
     */
    private void checkUnique(CarTypeLimit carTypeLimit) {
        CarTypeLimit tempCarTypeLimit;

        tempCarTypeLimit = carTypeLimit.getId() == null ?
                carTypeLimitRepository.findOne(JpaDsl.toCriteriaByEq(
                        "classify.id", carTypeLimit.getClassify().getId(),
                        "regProvince.id", carTypeLimit.getRegProvince().getId()
                )).orElse(null) :
                carTypeLimitRepository.findOne(JpaDsl.toCriteria(
                        "classify.id", "EQ", carTypeLimit.getClassify().getId(),
                        "regProvince.id", "EQ", carTypeLimit.getRegProvince().getId(),
                        "id", "NE", carTypeLimit.getId()

                )).orElse(null);
        if(tempCarTypeLimit != null) throw new RuntimeException("系统已存在相同商品分类，相同省份的数据");
    }

    /**
     * 暂停服务车型也可服务，返回真的话
     * @param area
     * @param classify
     * @return
     */
    public boolean isCarTypeLimit(Area area, Classify classify){
        List<CarTypeLimit> carTypeLimits =
                carTypeLimitRepository.findAll(JpaDsl.toCriteriaByEq("regProvince.id",area.getId(),"classify.id",classify.getId()));

        if(carTypeLimits.size() != 0) return true;
        return false;
    }
}
